package com.example.plugin_native.createFarm

import android.view.View
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import com.example.plugin_native.api.CreateFarmApi
import com.example.plugin_native.entity.FarmPrincipal
import com.example.plugin_native.entity.PlotInfoData
import com.example.plugin_native.entity.PlotType
import com.map.interfaces.Point
import com.map.utils.TransferOfAxesUtil
import com.support.base.*
import com.support.net.API
import com.support.net.Http
import com.support.net.Params

class CreateFarmModel : OurViewModel() {

    @API
    private lateinit var api: CreateFarmApi

    //UI底部按钮是否允许点击
    val startAndOverBtn = true.liveData
    val closeBtn = false.liveData
    val revocationBtn = false.liveData
    val recoverBtn = false.liveData

    val startAndOverText = "开始绘制".liveData

    //当前选中的类型
    var selectFarmType: Int = 0
    var selectFarmTypeIndex: Int = 0

    //当前选中的地块颜色
    val selectFarmColor = "#EE6C4B".obs
    val selectFarmColorLiveData = "#EE6C4B".liveData

    //当前输入的地块名称
    var createFarmName = ""

    //地块坐标
    private var plotPosition: String = "[]"

    //操作步骤提示语
    val stepOne = "第一步，点击'开始绘制'按钮"
    val stepTwo = "第二步，点击地图开始绘制"
    val stepThree = "第三步，再次点击起始点，可闭合田圈"
    val stepFour = "第四步，拖拽边界点，可编辑地块"

    //选中的地块负责人
    val farmPrincipal = "请选择".obs

    //选中的地块负责人，提交入参
    val farmPrincipalList = mutableListOf<String>()

    //地块标记：0:地块,1:房屋,2:植被
    val farmMark = mapOf(0 to "地块", 1 to "房屋", 2 to "植被")
    val selectMark = (0 to "地块").obs

    //当前操作步骤
    val alertInfo = stepOne.liveData

    //地块信息
    val plotInfoLiveData = MutableLiveData<ArrayList<PlotInfoData>>()

    //负责人信息
    val principalLiveData = MutableLiveData<ArrayList<FarmPrincipal>>()

    //地块类型信息
    val plotTypeLiveData = MutableLiveData<ArrayList<PlotType>>()

    //地块添加结果
    val isAddPlotSuc = MutableLiveData<Boolean>()

    /**
     * 设置地块经纬度
     */
    fun setPlotPosition(points: List<Point>) {
        val stringBuilder = StringBuilder().append("[")
        points.forEach {
            val lngLat = TransferOfAxesUtil.wgs84ToGcj02(lng = it.lng, lat = it.lat)
            stringBuilder
                .append("\"")
                .append(lngLat[1])
                .append(",")
                .append(lngLat[0])
                .append("\"")
                .append(",")
        }

        plotPosition = stringBuilder.substring(0, stringBuilder.length - 1) + "]"
    }

    /**
     * 获取地块信息
     */
    fun getPlotInfo() {
        verify(
            suc = {
                plotInfoLiveData set it
            },
            fail = {
                showToast(it)
            }) {
            api.findFarmProcessingPlanList(
                param = Params.get(
                    "farmCode" to Http.farmCode,
                    "jdPin" to Http.pin
                )
            )
        }
    }

    /**
     * 获取农场人员列表
     */
    fun findFarmUsers() {
        showLoading("正在加载")
        verify(
            suc = {
                dismissLoading()
                principalLiveData set it
            },
            fail = {
                dismissLoading()
            }) {
            api.findFarmUsers(
                param = Params.get(
                    "farmCode" to Http.farmCode,
                    "userPin" to Http.pin
                )
            )
        }
    }

    /**
     * 获取地块类型
     */
    fun getPlotTypes() {
        //避免数据重复请求，增加用户体验
        if (plotTypeLiveData.value != null) {
            plotTypeLiveData.value!![selectFarmTypeIndex].isSelect = true
            selectFarmType = plotTypeLiveData.value!![selectFarmTypeIndex].plotType
            plotTypeLiveData set plotTypeLiveData.value!!
            return
        }
        showLoading("正在加载")
        verify(
            suc = {
                dismissLoading()
                it[selectFarmTypeIndex].isSelect = true
                selectFarmType = it[selectFarmTypeIndex].plotType
                plotTypeLiveData set it
            },
            fail = {
                showToast(it)
                dismissLoading()
            }) {
            api.getPlotTypes()
        }
    }

    /**
     * 添加地块
     */
    fun addPlot(plotName: String, plotArea: Double) {
        showLoading("正在添加")
        verify(
            suc = {
                dismissLoading()
            },
            empty = {
                showToast("添加成功")
                isAddPlotSuc set true
                dismissLoading()
            },
            fail = {
                showToast(it)
                isAddPlotSuc set false
                dismissLoading()
            }) {
            api.addPlot(
                param = Params.get(
                    "color" to selectFarmColor.value,//地块颜色
                    "plotType" to selectFarmType,//地块类型
                    "plotName" to plotName,//地块名称
                    "plotArea" to plotArea,//地块面积	单位（亩）
                    "plotPosition" to plotPosition,//地块坐标	[\"49.54240868154162,120.34903076550417\",...]"
                    "marker" to selectMark.value.first,//标记 0:地块,1:房屋,2:植被
                    "farmers" to farmPrincipalList,//地块负责人
                    "userPin" to Http.pin,//京东pin
                    "farmCode" to Http.farmCode,//农场编码
                )
            )
        }
    }

    /**
     * 点击事件
     */
    fun onClick(view: View) {
        when (view) {
            is ImageView -> {
                selectFarmColor.value = view.tag.toString()
                selectFarmColorLiveData set view.tag.toString()
            }
        }
    }
}